<?php

// 雪里开简易预约制访客管理系统 V1.0（2025.05.20）
// 演示地址: http://fangke.chalide.cn
// 更新关注: /weivote/yuyuefangke
// 文件路径: sus/vist.php
// 文件大小: 16279 字节
// 最后修改时间: 2025-05-20 22:29:00
// 作者: yujianyue
// 邮件: 15058593138@qq.com
// 版权所有,保留发行权和署名权
/**
 * 门卡管理员访客核销
 * 功能反馈:15058593138@qq.com
 */

// 获取分页参数
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$page = max(1, $page);
$pageSize = 10;

// 获取搜索参数
$search_field = get_param('search_field', 'vname');
$search_value = get_param('search_value', '');

// 获取当前门卡管理员账号
$huser = $_SESSION['user_name'] . '(' . get_param('user_xh', '') . ')';

// 处理AJAX请求
if (isset($_GET['act'])) {
    $db = new MySQLDB();
    
    switch ($_GET['act']) {
        case 'search':
            // 获取访客码
            $vcode = post_param('vcode');
            
            // 简单验证
            if (!$vcode) {
                json_error('访客码不能为空');
            }
            
            // 查询访客信息
            $sql = "SELECT v.*, s.name as stu_name, s.xh as stu_xh 
                    FROM `vist` v 
                    LEFT JOIN `stux` s ON v.stuid = s.id 
                    WHERE v.vcode = '" . $db->escape($vcode) . "'";
            $row = $db->getOne($sql);
            
            if (!$row) {
                json_error('未找到该访客码对应的记录');
            }
            
            // 检查是否已核销
            if ($row['htime']) {
                json_error('该访客码已被核销，核销时间：' . format_date($row['htime'], 'Y-m-d H:i:s'));
            }
            
            json_success('查询成功', $row);
            break;
            
        case 'verify':
            // 获取访客ID
            $id = post_param('id');
            
            // 简单验证
            if (!$id) {
                json_error('ID不能为空');
            }
            
            // 查询访客信息
            $row = $db->getOne("SELECT * FROM `vist` WHERE `id` = '$id'");
            
            if (!$row) {
                json_error('未找到记录');
            }
            
            // 检查是否已核销
            if ($row['htime']) {
                json_error('该记录已被核销，核销时间：' . format_date($row['htime'], 'Y-m-d H:i:s'));
            }
            
            // 更新核销信息
            $data = [
                'htime' => date('Y-m-d H:i:s'),
                'huser' => $_SESSION['user_name']
            ];
            
            $result = $db->update('vist', $data, "id = '$id'");
            
            if ($result) {
                json_success('核销成功');
            } else {
                json_error('核销失败：' . $db->getError());
            }
            break;
            
        case 'detail':
            // 获取参数
            $id = post_param('id');
            
            // 简单验证
            if (!$id) {
                json_error('ID不能为空');
            }
            
            // 查询详情
            $sql = "SELECT v.*, s.name as stu_name, s.xh as stu_xh 
                    FROM `vist` v 
                    LEFT JOIN `stux` s ON v.stuid = s.id 
                    WHERE v.id = '$id'";
            $row = $db->getOne($sql);
            
            if ($row) {
                json_success('获取成功', $row);
            } else {
                json_error('获取失败：记录不存在');
            }
            break;
    }
    exit;
}

// 加载页头
require_once './inc/head.php';

// 构建查询条件
$where = "huser = '" . $db->escape($_SESSION['user_name']) . "'";
if ($search_value) {
    $search_value = $db->escape($search_value);
    
    switch ($search_field) {
        case 'vname':
            $where .= " AND vname LIKE '%$search_value%'";
            break;
        case 'vtel':
            $where .= " AND vtel LIKE '%$search_value%'";
            break;
        case 'vcode':
            $where .= " AND vcode LIKE '%$search_value%'";
            break;
    }
}

// 获取分页数据
$start = ($page - 1) * $pageSize;

// 查询总数
$count_sql = "SELECT COUNT(*) as total 
              FROM `vist` 
              WHERE $where";
$count_result = $db->getOne($count_sql);
$total = $count_result ? $count_result['total'] : 0;
$totalPage = ceil($total / $pageSize);

// 查询列表
$sql = "SELECT v.*, s.name as stu_name, s.xh as stu_xh 
        FROM `vist` v 
        LEFT JOIN `stux` s ON v.stuid = s.id 
        WHERE $where 
        ORDER BY v.htime DESC 
        LIMIT $start, $pageSize";
$list = $db->getAll($sql);
?>

<div class="container">
    <div class="search-bar">
        <div class="row" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
            <div class="col-left">
                <h2 style="margin: 0;">访客核销</h2>
            </div>
        </div>
    </div>
    
    <div class="card" style="background-color: #f5f5f5; padding: 15px; margin-bottom: 20px; border-radius: 4px;">
        <div style="display: flex; flex-wrap: wrap; margin-bottom: 10px;">
            <input type="text" id="vcode-input" class="form-control" placeholder="请输入访客码" style="flex: 1; margin-right: 10px; min-width: 200px;">
            <button type="button" id="search-btn" class="btn btn-primary">查询</button>
        </div>
        <div id="scan-result" style="display: none;"></div>
    </div>
    
    <div class="search-bar">
        <div class="row" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
            <div class="col-left">
                <h3 style="margin: 0;">核销记录</h3>
            </div>
        </div>
        
        <form action="" method="get" class="search-form" style="display: flex; margin-bottom: 15px;">
            <input type="hidden" name="do" value="vist">
            <select name="search_field" class="search-select">
                <option value="vname" <?php echo $search_field == 'vname' ? 'selected' : ''; ?>>访客姓名</option>
                <option value="vtel" <?php echo $search_field == 'vtel' ? 'selected' : ''; ?>>访客电话</option>
                <option value="vcode" <?php echo $search_field == 'vcode' ? 'selected' : ''; ?>>访客码</option>
            </select>
            <input type="text" name="search_value" class="search-input" placeholder="请输入搜索内容" value="<?php echo htmlspecialchars($search_value); ?>">
            <button type="submit" class="search-btn">查询</button>
        </form>
    </div>
    
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>学生信息</th>
                    <th>访客姓名</th>
                    <th>访客电话</th>
                    <th>目标宿舍</th>
                    <th>访客码</th>
                    <th>核销时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($list)): ?>
                <?php foreach ($list as $item): ?>
                <tr>
                    <td><?php echo $item['id']; ?></td>
                    <td>
                        <?php echo htmlspecialchars($item['stu_name'] ?: '-'); ?><br>
                        <small><?php echo htmlspecialchars($item['stu_xh'] ?: '-'); ?></small>
                    </td>
                    <td><?php echo htmlspecialchars($item['vname']); ?></td>
                    <td><?php echo htmlspecialchars($item['vtel']); ?></td>
                    <td><?php echo htmlspecialchars($item['room']); ?></td>
                    <td><?php echo htmlspecialchars($item['vcode']); ?></td>
                    <td><?php echo format_date($item['htime'], 'Y-m-d H:i'); ?></td>
                    <td>
                        <button type="button" class="btn btn-default btn-sm" onclick="showDetail(<?php echo $item['id']; ?>)">详情</button>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php else: ?>
                <tr>
                    <td colspan="8" align="center">暂无数据</td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($total > 0): ?>
    <div class="table-footer">
        <div class="table-info">共 <?php echo $total; ?> 条记录，第 <?php echo $page; ?>/<?php echo $totalPage; ?> 页</div>
        <?php echo paginate($page, $totalPage, '?do=vist&search_field=' . urlencode($search_field) . '&search_value=' . urlencode($search_value)); ?>
    </div>
    <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 查询按钮点击事件
    document.getElementById('search-btn').addEventListener('click', searchVisitor);
    
    // 回车键查询
    document.getElementById('vcode-input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchVisitor();
        }
    });
});

// 查询访客
function searchVisitor() {
    const vcode = document.getElementById('vcode-input').value.trim();
    if (!vcode) {
        showToast('请输入访客码', 'warning');
        return;
    }
    
    // 清空之前的结果
    document.getElementById('scan-result').innerHTML = '';
    document.getElementById('scan-result').style.display = 'none';
    
    // 发送查询请求
    ajaxRequest('?do=vist&act=search', {vcode: vcode}, function(res) {
        if (res.code === 0) {
            const data = res.data;
            
            // 显示查询结果
            let resultHtml = `
            <div class="card" style="background-color: #fff; padding: 15px; margin-top: 10px; border-radius: 4px; border: 1px solid #ddd;">
                <div style="display: flex; justify-content: space-between; align-items: flex-start;">
                    <div>
                        <h3 style="margin-top: 0; margin-bottom: 10px;">访客信息</h3>
                        <p><strong>访客姓名：</strong>${data.vname}</p>
                        <p><strong>访客电话：</strong>${data.vtel}</p>
                        <p><strong>到访日期：</strong>${formatDate(data.vdate)}</p>
                        <p><strong>目标宿舍：</strong>${data.room}</p>
                        <p><strong>到访事由：</strong>${data.reason}</p>
                    </div>
                    <div style="text-align: center;">
                        <div class="visit-code">${data.vcode}</div>
                    </div>
                </div>
                <div style="text-align: center; margin-top: 15px;">
                    <button type="button" class="btn btn-success" onclick="verifyVisitor(${data.id})">确认核销</button>
                </div>
            </div>
            `;
            
            document.getElementById('scan-result').innerHTML = resultHtml;
            document.getElementById('scan-result').style.display = 'block';
        } else {
            showToast(res.msg, 'error');
        }
    });
}

// 核销访客
function verifyVisitor(id) {
    if (!id) return;
    
    confirmDialog('确定要核销此访客吗？', function() {
        ajaxRequest('?do=vist&act=verify', {id: id}, function(res) {
            if (res.code === 0) {
                showToast(res.msg, 'success');
                
                // 清空输入框和结果
                document.getElementById('vcode-input').value = '';
                document.getElementById('scan-result').innerHTML = '';
                document.getElementById('scan-result').style.display = 'none';
                
                // 刷新页面
                setTimeout(function() {
                    window.location.reload();
                }, 1500);
            } else {
                showToast(res.msg, 'error');
            }
        });
    });
}

// 显示详情
function showDetail(id) {
    ajaxRequest('?do=vist&act=detail', {id: id}, function(res) {
        if (res.code === 0) {
            const data = res.data;
            
            let content = `
            <div class="detail-section">
                <h3 class="detail-title">学生信息</h3>
                <div class="detail-item">
                    <div class="detail-label">姓名:</div>
                    <div class="detail-value">${data.stu_name || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">学号:</div>
                    <div class="detail-value">${data.stu_xh || '-'}</div>
                </div>
            </div>
            
            <div class="detail-section">
                <h3 class="detail-title">访客信息</h3>
                <div class="detail-item">
                    <div class="detail-label">姓名:</div>
                    <div class="detail-value">${data.vname}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">电话:</div>
                    <div class="detail-value">${data.vtel}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">目标宿舍:</div>
                    <div class="detail-value">${data.room}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">到访日期:</div>
                    <div class="detail-value">${formatDate(data.vdate)}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">到访事由:</div>
                    <div class="detail-value">${data.reason}</div>
                </div>
            </div>
            
            <div class="detail-section">
                <h3 class="detail-title">访客码</h3>
                <div class="visit-code">${data.vcode}</div>
            </div>
            
            <div class="detail-section">
                <h3 class="detail-title">核销信息</h3>
                <div class="detail-item">
                    <div class="detail-label">核销时间:</div>
                    <div class="detail-value">${formatDateTime(data.htime)}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">核销账号:</div>
                    <div class="detail-value">${data.huser || '-'}</div>
                </div>
            </div>
            `;
            
            showMask(content, '访客详情', [
                {
                    text: '关闭',
                    class: 'mask-button-default',
                    click: closeMask
                }
            ]);
        } else {
            showToast(res.msg, 'error');
        }
    });
}

// 格式化日期
function formatDate(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.getFullYear() + '-' + 
           String(date.getMonth() + 1).padStart(2, '0') + '-' + 
           String(date.getDate()).padStart(2, '0');
}

// 格式化日期时间
function formatDateTime(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.getFullYear() + '-' + 
           String(date.getMonth() + 1).padStart(2, '0') + '-' + 
           String(date.getDate()).padStart(2, '0') + ' ' +
           String(date.getHours()).padStart(2, '0') + ':' +
           String(date.getMinutes()).padStart(2, '0') + ':' +
           String(date.getSeconds()).padStart(2, '0');
}
</script>

<style>
.detail-section {
    margin-bottom: 20px;
}
.detail-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
    padding-bottom: 5px;
    border-bottom: 1px solid #eee;
}
.detail-item {
    display: flex;
    margin-bottom: 8px;
}
.detail-label {
    width: 80px;
    font-weight: bold;
}
.detail-value {
    flex: 1;
}
.table-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    padding: 10px 0;
}
.table-info {
    margin-bottom: 10px;
}
.visit-code {
    text-align: center;
    font-size: 24px;
    font-weight: bold;
    padding: 15px;
    background-color: #f5f5f5;
    border-radius: 4px;
    letter-spacing: 2px;
    margin-bottom: 10px;
}
</style>
